<?php
/**
 * 采集类
 *
 */
class Collection
{

	var $src = "";
	var $path;
	var $root;
	var $value;
	var $try = 0;
	var $charset = 'UTF-8';
	
	
	function __construct(){
		
		$this->tags = '{DATA}';
	
	}
	
	/**
	 * 设置目标的编码
	 *
	 */
	function setCharset($charset)
	{
		$this->charset = $charset;
	}
	/**
	 * 获取远端的内容
	 *
	 */
	function getPageContent($url)
	{

		
		$this->getUrl($url);
		
		$url_parsed = parse_url($url);
		$host = $url_parsed['host'];
		$port = $url_parsed['port'];
		
		if ( $port == 0 )
		{
			$port = 80;
		}
		
		$path = $url_parsed['path'];
		
		if (empty($path))
		{
			$path = "/";
		}
		
		if ( $url_parsed['query'] != "" )
		{
			$path .= "?".$url_parsed['query'];
		}
		
		$out = "GET {$path} HTTP/1.0\r\nHost: {$host}\r\n\r\n";

		if ($fp = @fsockopen( $host, $port, $errno, $errstr, 30 ))
		{
			
			fwrite($fp,$out);
			$body = false;
			while (!feof($fp))
			{
				$s = fgets($fp,1024);

				if ($body)
				{
					$in .= $s;
				}
				if ( $s == "\r\n" )
				{
					$body = true;
				}
			}
			fclose($fp);

			if($this->charset !='UTF-8')
			{
				$in = iconv($this->charset,'UTF-8',$in);
			}
			
			$this->value = $in;
			
			return $in;
		}
		else
		{
			return false;
		}
	}

	/**
	 * 解析远端地址的根地址
	 *
	 */
	function getUrl($url)
	{

		$url = substr( $url, 0, 7 ) != "http://" ? "http://".$url : $url;
		$this->src = $url;
		$this->path = substr( $this->src, 0, strrpos( $this->src, "/" ) + 1 );
		$url = parse_url( $url );
		$this->root = "http://".$url['host']."/";
		
	}

	//过滤替换函数
	function change($oldStr,$str,$value)
	{
		if(empty($value)) $value = $this->value;
		return str_replace( $oldStr, $str, $value);
	}

	/**
	 * 过滤替换函数
	 *
	 * @param 
	 * 
	 * $content 传入的替换规则
	 * $str 替换后的结果
	 * 
	 * <title>{DATA} - * </title>
	 * 
	 * @param unknown_type $str
	 */
	function changePreg($content,$str,$value)
	{
		
		if(empty($value)) $value = $this->value;
		
		$pattern = str_replace( "*", "(?:.*?)", $content);
		$pattern = str_replace( $this->tags, "(.*?)", $pattern );
		
		@preg_match( "|{$pattern}|is", $value, $mt);
		
		$value = str_replace($mt[1], $str, $value);

		$clear_content = explode($this->tags,$content);
		
		$value = str_replace($clear_content['0'],'',$value);
		$value = str_replace($clear_content['1'],'',$value);
		
		return $value;

	}
	
	
	//截取函数
	
	function Cut( $start, $end, $no = "1", $comprise = "" )
	{
		$string = explode($start, $this->value );
		$string = explode($end, $string[$no] );
		switch ( $comprise )
		{
		case "start" :
			$string = $start.$string[0];
			break;
		case "end" :
			$string = $string[0].$end;
			break;
		case "all" :
			$string = $start.$string[0].$end;
			break;
		default :
			$string = $string[0];
		}
		return $string;
	}

	/**
	 * 分析远端地址列表
	 *
	 */
	function parseUrl($content)
	{
		$chr = array(
			"\$",
			"+",
			"?",
			"^",
			")",
			"(",
			"{",
			"}"
		);
		$pattern = str_replace( "*", "(?:.*?)", $content);
		$pattern = str_replace( $this->tags, "(.*?)", $pattern );

		@preg_match_all( "|{$pattern}|is", $this->value, $content, PREG_PATTERN_ORDER );

		
		$pagenum = count($content[1]);

		for ($i=0;$i<$pagenum;$i++)
		{
			if (substr($content[1][$i], 0, 1 ) == "/" )
			{
				$url_array[$i] = $this->root.$content[1][$i];
			}
			else if ( !eregi( "://", $content[1][$i] ) )
			{
				$url_array[$i] = $this->path.$content[1][$i];
			}
			

			$list[] = str_replace('//','/',$url_array[$i]);
		}
		
		$this->urllist = $list;

		return 	$list;
	}

	/**
	 * 截取内容
	 *
	 */
	function filtrateContent($content, $clean_html = "0")
	{
		
		$pattern = str_replace( "*", "(?:.*?)", $content );
		$pattern = str_replace( $this->tags, "(.*?)", $pattern );

		@preg_match( "|{$pattern}|is", $this->value, $content );
		
		$content = trim( $content[1] );
		if ( $clean_html == "1" )
		{
			$content = strip_tags( $content, "<br><br /><p></p><img" );
		}

		return $content;
	}

	
	/**
	 * 保存图片等小文件
	 *
	 */
	function saveFile($file, $path, $try = 0 )
	{
		
		if ($try > 5)
		{
			$try = 5;
		}
		if (!is_dir($path))
		{
			$this->createdir($path);
		}
		
		$data = $this->referfile($file,$this->root);
		
		if (!$data)
		{
			if ($this->try < intval( $try ) )
			{
				$this->try ++;
				$this->savefile($file,$path);
			}
			else
			{
				$this->try = 0;
			}
		}

		$ext = substr(strrchr(urldecode($file), "."), 0,4);
		$filename = date( "Ymdhis", time( ) ).$this->makename(8).$ext;
		$filepath = $path."/".$filename;

		fclose(fwrite(fopen($filepath, "w+" ), $data));
		
		if ( 0 < filesize($filepath))
		{
			return $filename;
		}
		else
		{
			@unlink($filepath);
			return false;
		}
	}

	function makeName( $length )
	{
		$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$str = "";
		while ( strlen( $str ) < $length )
		{
			$str .= substr( $possible, rand( ) % strlen( $possible ), 1 );
		}
		return $str;
	}

	function createdir( $dir )
	{
		if ( !is_dir( $dir ) )
		{
			$temp = explode( "/", $dir );
			$cur_dir = "";
			for ($i = 0;i < count( $temp );	++$i	)
			{
				$cur_dir .= $temp[$i]."/";
				if ( !is_dir( $cur_dir ) )
				{
					@mkdir($cur_dir, 0755 );
				}
			}
		}
	}
	
	function referfile($url,$refer='') {
        $opt=array('http'=>array('header'=>"Referer:" . $refer));
        $context=stream_context_create($opt);
        return file_get_contents($url,false,$context);
	}
	
	function debug( )
	{
		$tempstr = "<SCRIPT>function runEx(){var winEx2 = window.open(\"\", \"winEx2\", \"width=500,height=300,status=yes,menubar=no,scrollbars=yes,resizable=yes\"); winEx2.document.open(\"text/html\", \"replace\"); winEx2.document.write(unescape(event.srcElement.parentElement.children[0].value)); winEx2.document.close(); }function saveFile(){var win=window.open('','','top=10000,left=10000');win.document.write(document.all.asdf.innerText);win.document.execCommand('SaveAs','','javascript.htm');win.close();}</SCRIPT><center><TEXTAREA id=asdf name=textfield rows=32  wrap=VIRTUAL cols=\"120\">".$this->value."</TEXTAREA><BR><BR><INPUT name=Button onclick=runEx() type=button value=\"查看效果\">&nbsp;&nbsp;<INPUT name=Button onclick=asdf.select() type=button value=\"全选\">&nbsp;&nbsp;<INPUT name=Button onclick=\"asdf.value=''\" type=button value=\"清空\">&nbsp;&nbsp;<INPUT onclick=saveFile(); type=button value=\"保存代码\"></center>";
		echo $tempstr;
	}

}

?>
